package edu.hut.bookshop.service.impl;

import edu.hut.bookshop.dao.AdminMapper;
import edu.hut.bookshop.exception.CustomizeException;
import edu.hut.bookshop.pojo.Admin;
import edu.hut.bookshop.service.IAdminService;
import edu.hut.bookshop.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AdminServiceImpl implements IAdminService {

    @Resource
    private AdminMapper adminMapper;

    @Override
    public Integer regad(Admin admin) {
        //通过user参数来获取传递过来的username
        String username = admin.getAdname();
        //先做判断,调用findByUsername(username)判断用户是否被注册过
        Admin result = adminMapper.findByAdminname(username);
        //判断结果集不为null则抛出用户名被占用的异常
        if(result!=null){
            //抛出异常
            System.out.println("该管理员名字被占用");

        }

        //执行注册业务功能的实现(rows==1)
        Integer rows = adminMapper.insertAdmin(admin);
        if(rows!=1){
            System.out.println("管理员在注册过程中产生了未知的异常");
        }
        return rows;
    }

    @Override
    public Admin login(String adname, String password) {

        //根据用户名称来查询用户的数据是否存在，如果不存在则抛出异常
        Admin result =adminMapper.findByAdminname(adname);
        if(result==null){
            throw new CustomizeException(ResultCode.USER_NOT_FOUND);
        }

        if(!result.getPassword().equals(password)){
            throw new CustomizeException(ResultCode.PASSWORD_ERROR);
        }

        Admin admin = new Admin();
        admin.setAdid(result.getAdid());
        admin.setAdname(result.getAdname());
        return admin;
    }
}
